<script lang="tsx">
import { defineComponent, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Eye, FileText, SvgRefundIcon } from '@vben/icons';
import { usePage } from '#/hooks/page/usePage';
import { getCertOrderDetailApi, getOrderListApi, getOrderStatusDetailApi, exportCertOrderExcelApi, certOrderRefundApi } from '#/api/pay/order';
import { getCertifiedListApi } from '#/api/certificate/list';
import { exportDownload } from '#/components/common/hooks/useExport';

export default defineComponent({
  name: 'Order',
  setup() {
    const certifiedList = ref({
      prop: 'certificateId',
      label: '认证名称',
      placeholder: '请选择',
      options: [],
    });
    const orderStatus = ref({
      prop: 'status',
      label: '订单状态',
      placeholder: '请选择',
      options: [],
    });
    // API配置
    const API = {
      get: (params: any) => {
        if (params.time) {
          const [startTime, endTime] = params.time;
          params.startTime = startTime;
          params.endTime = endTime;
        }
        delete params.time;
        return getOrderListApi(params)
      }
    };

    const getOrderStatus = async () => {
      const res = await getOrderStatusDetailApi();
      orderStatus.value.options = res.map((item: any) => ({
        label: item.desc,
        value: item.status
      }));
    };

    const getCertifiedList = async () => {
      const res = await getCertifiedListApi({});
      certifiedList.value.options = res.data.map((item: any) => ({
        label: item.name,
        value: item.id
      }));
    };

    onMounted(() => {
      getOrderStatus();
      getCertifiedList();
    });

    // 获取状态颜色和文本
    const getStatusInfo = (status: string) => {
      const statusMap: Record<string, { color: string; text: string; hasIcon?: boolean }> = {
        pending: { color: '#FB9A0E', text: '待支付' },
        pay_success: { color: '#30A46C', text: '已支付' },
        refund_processing: { color: '#0067D1', text: '退款中' },
        refund_success: { color: '#0067D1', text: '退款成功' },
        refund_fail: { color: '#E5484D', text: '退款失败' },
        expired: { color: '#AEAEAE', text: '已过期' },
      };
      return statusMap[status] || { color: 'bg-gray-500', text: '未知' };
    };

    // 表格列配置
    const columns = () => {
      return [
        {
          prop: 'orderNo',
          label: '订单编号',
          minWidth: 180,
          showOverflowTooltip: true,
          componentName: 'el-text',
          render: (row: any) => row.orderNo ?? '-'
        },
        {
          prop: 'certificateName',
          label: '认证名称',
          minWidth: 180,
          showOverflowTooltip: true,
          componentName: 'el-text',
          render: (row: any) => row.certificateName ?? '-'
        },
        {
          prop: 'userName',
          label: '姓名',
          minWidth: 90,
          componentName: 'el-text',
          render: (row: any) => row.userName ?? '-'
        },
        {
          prop: 'phone',
          label: '联系方式',
          minWidth: 110,
          showOverflowTooltip: true,
          componentName: 'el-text',
          render: (row: any) => row.phone ?? '-'
        },
        {
          prop: 'targetPrice',
          label: '目录价格',
          minWidth: 80,
          componentName: 'el-text',
          render: (row: any) => row.targetPrice ?? '-'
        },
        {
          prop: 'discountPrice',
          label: '优惠价格',
          minWidth: 90,
          showOverflowTooltip: true,
          componentName: 'el-text',
          render: (row: any) => row.discountPrice ?? '-'
        },
        {
          prop: 'amount',
          label: '实付金额',
          minWidth: 80,
          componentName: 'el-text',
          render: (row: any) => row.amount ?? '-'
        },
        {
          prop: 'statusDesc',
          label: '订单状态',
          minWidth: 120,
          formatter: (row: any) => {
            const statusInfo = getStatusInfo(row.status);
            return (
              <div class="flex items-center">
                <div
                  class="w-2 h-2 rounded-full mr-2"
                  style={{ backgroundColor: statusInfo.color }}
                ></div>
                <span>{row.statusDesc}</span>
              </div>
            );
          },
          componentName: 'el-text',
          render: (row: any) => row.statusDesc ?? '-'
        },
        {
          prop: 'createTime',
          label: '创建时间',
          minWidth: 180,
          showOverflowTooltip: true,
          componentName: 'el-text',
          render: (row: any) => row.createTime ?? '-'
        },
        {
          prop: 'payTime',
          label: '支付时间',
          minWidth: 180,
          showOverflowTooltip: true,
          componentName: 'el-text',
          render: (row: any) => row.payTime ?? '-'
        },
        {
          prop: 'payOptionDesc',
          label: '支付方式',
          minWidth: 120,
          showOverflowTooltip: true,
          componentName: 'el-text',
          render: (row: any) => row.payOptionDesc ?? '-'
        }
      ];
    }

    // 查询配置
    const queryColumns = [
      {
        prop: 'orderNo',
        label: '订单编号',
        type: 'input',
        placeholder: '请输入',
      },
      certifiedList.value,
      {
        prop: 'userName',
        label: '姓名',
        type: 'input',
        placeholder: '请输入',
      },
      {
        prop: 'phone',
        label: '联系方式',
        type: 'input',
        placeholder: '请输入',
      },
      orderStatus.value,
      {
        prop: 'time',
        label: '支付时间',
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        format: 'YYYY-MM-DD HH:mm:ss',
        style: { width: `calc((100% - 14px)/2)` }
      }
    ];

    // 操作按钮配置
    const commands = [
      {
        key: 'refund',
        width: 40,
        // label: '申请退款',
        // icon: SvgRefundIcon,
        render: (row: any) => {
          return (
            <el-tooltip content="申请退款">
              <el-button type="primary"
                onClick={() => handleCommand('refund', row)}
                disabled={!['pay_success', 'refund_fail'].includes(row.status)}
                link icon={SvgRefundIcon}>
              </el-button>
            </el-tooltip>
          )
        }
      },
      {
        key: 'detail',
        width: 40,
        label: '订单详情',
        icon: FileText,
      },
    ];
    const initForm = (title: string, disabled: boolean = false) => {
      formState.visible = true;
      formState.title = title;
      formState.width = '800px';
      formState.formProps.labelPosition = 'left';
      formState.formProps.inline = true;
      formState.formProps.disabled = disabled;
      formState.formProps.columns = columns()
    }

    const orderDetail = (orderId: string) => {
      return getCertOrderDetailApi({
        orderId: orderId || ''
      })
    }
    // 自定义操作处理
    const handleCommand = (type: string, data?: any, index?: number) => {
      // formState.formProps.loading = true
      orderDetail(data.orderId).then((data: any) => {
        formState.data = data
      }).finally(() => {
        // formState.formProps.loading = false
      })
      if (type === 'refund') {
        initForm('申请退款', false);
        formState.formProps.columns.push(...[{
          prop: 'amount',
          label: '退款金额',
          type: 'number',
          formItemProps: {
            style: {
              width: '100%'
            }
          },
          render: (row: any) => row.amount ?? '-'
        },
        {
          prop: 'refundReason',
          label: '退款原因',
          required: true,
          type: 'textarea',
          placeholder: '请输入退款原因',
          formItemProps: {
            style: {
              width: '100%'
            }
          },
        }
        ])
      } else if (type === 'detail') {
        initForm('订单详情', true);
        if (data.status === 'refund_success') {
          formState.formProps.columns.push(...[{
            prop: 'refundReason',
            label: '退款原因',
            componentName: 'el-text',
            render: (row: any) => row.refundReason ?? '-'
          }])
        }
      }
    };

    const { render, tableHandle, getTableData, formState, queryState, selection } = usePage({
      API,
      operateProps: {
        fixed: 'right',
      },
      columns: columns(),
      queryColumns,
      commands,
      handleCommand,
      query: {},
      prefix: () => <el-table-column type="selection" width="45" />
    });

    formState.onSubmit = (data: any) => {
      certOrderRefundApi({
        orderId: data.orderId || '',
        refundReason: data.refundReason,
        refundAmt: data.amount
      }).then((res: any) => {
        ElMessage.success('退款成功');
        formState.visible = false;
        getTableData()
      })
    }

    // 下载功能
    const handleDownload = () => {
      const certOrderIds = selection.value.map((item: any) => item.orderId);
      exportCertOrderExcelApi(certOrderIds).then((res: any) => {
        exportDownload(res.data, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '订单数据.xlsx');
      });
    };

    return () => (render({
      header: (
        <el-button type="primary" onClick={handleDownload} disabled={selection.value.length === 0}>下载</el-button>)
    })
    );
  }
});
</script>

<style scoped lang="scss"></style>
